package com.ctgu.project.mq;

import com.ctgu.project.utils.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

/**
 * @ClassName SortSetController
 * @Author Alex2
 * @Date 2025/2/28 17:13
 **/
@RequestMapping("/api/sortSet")
@RestController
public class SortSetController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String REDIS_KEY_MQ_SORT_SET = "mq:sortSet:1001";

    // http://localhost:8080/api/sortSet/producer/hello/2
    @GetMapping("producer/{message}/{priority}")
    public ApiResult producer(@PathVariable String message, @PathVariable double priority) {
        stringRedisTemplate.opsForZSet().add(REDIS_KEY_MQ_SORT_SET, message, priority);
        return ApiResult.success("生产新消息成功", message);
    }

    // http://localhost:8080/api/sortSet/consumer
    @GetMapping("consumer")
    public ApiResult consumer() {
        // popMin 避免高并发场景下的重复消费
        Set<ZSetOperations.TypedTuple<String>> tuples = stringRedisTemplate.opsForZSet().popMin(REDIS_KEY_MQ_SORT_SET, 1);
        if (tuples != null && !tuples.isEmpty()) {
            String message = (String) tuples.iterator().next().getValue();
            return ApiResult.success("消费成功", message);
        } else {
            return ApiResult.success("所有消息均已消费，消息队列为空");
        }
    }
}